package com.css.common.core.utils.sign;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AES256Utils {
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";

    private static final String CHARSET="UTF-8";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";


    private static SecretKeySpec getSecretKey(String key) {
        return new SecretKeySpec(MD5Utils.encode(key).toLowerCase().getBytes(), ALGORITHM);
    }

    /**
     * AES加密
     *
     * @param data data
     * @param key  key
     * @return encrypt data
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws NoSuchPaddingException,
            NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException, UnsupportedEncodingException {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
        return Base64Utils.encode(cipher.doFinal(data.getBytes(CHARSET)));
    }

    /**
     * AES解密
     *
     * @param data data
     * @param key  key
     * @return str
     * @throws UnsupportedEncodingException 
     * @throws Exception 异常
     */
    public static String decrypt(String data, String key) throws NoSuchPaddingException,
            NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
        return new String(cipher.doFinal(Base64Utils.decode(data)),CHARSET);
    }

}
